package com.zang.linkedlist;

/**
 * @author ZVerify
 * @see <a href="https://leetcode.cn/problems/linked-list-cycle-ii/">...</a>
 * @since 2022/10/12 09:56
 **/
public class 环形链表II {

    public ListNode detectCycle(ListNode head) {

        if (head == null || head.next == null) {
            return null;
        }

        ListNode fast = head;
        ListNode slow = head;

        boolean flag = false;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;

            if (fast == slow) {
                flag = true;
                break;
            }
        }
        if (flag) {
            fast = head;
            while (slow != fast) {
                fast = fast.next;
                slow = slow.next;
            }
            return fast;
        } else {
            return null;
        }
    }
}
